<script setup>
// 控制对话框的显示与隐藏,默认隐藏
import { computed, ref, watch } from 'vue'
import { addAirData, listDistrict, updateAirDataInfo } from '@/api/air.js'
import { useCustomToast } from '@/util/custom-toast.js'

const props = defineProps({
  header: {
    type: String,
    default: '新增'
  },
  airDataInfo: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

// 子组件向父组件传递数据
const emit = defineEmits(['clearAirData', 'refreshAirDataList'])
// 显示or隐藏添加或者修改的对话框,默认隐藏
const showDialog = defineModel({ type: Boolean })

// 对话框标题
const header = computed(() => props.header)

// 空气质量数据信息
const airDataInfo = computed(() => props.airDataInfo)

// 区域列表
const districtList = ref([])

// 选中当前区域
const selectedDistrict = ref(null)

// 表单提交验证,默认关闭
const submitted = ref(false)

// 获取错误提示消息
const { showSuccess, showWarn, showError } = useCustomToast()

/**
 * 获取区域列表数据
 */
const getDistrictListData = () => {
  listDistrict().then(res => {
    if (res.code === 0) {
      districtList.value = res.data
    }
  })
}
// 调用区域列表函数
getDistrictListData()

// 监听区域的值
watch(airDataInfo, (newValue, oldValue) => {
  // 判断对象是否为空
  if (Object.keys(oldValue).length === 0) {
    districtList.value.forEach(item => {
      if (item.name === newValue.districtName) {
        // 构造对象
        const data = {}
        data.id = item.id
        data.name = item.name
        selectedDistrict.value = data
      }
    })
  }
}, { deep: true })

/**
 * 取消操作
 */
const cancelOperation = () => {
  showDialog.value = false
}

/**
 * 确认操作
 */
const confirmOperation = () => {
  if (airDataInfo.value.id) {
    // 调用修改的函数
    updateAirData()
  } else {
    // 调用新增的函数
    insertAirData()
  }
}

/**
 * 新增空气数据信息
 */
const insertAirData = () => {
  // 1.开启表单验证
  submitted.value = true

  // 2.判断是否选中区域
  if (selectedDistrict.value?.id !== null && selectedDistrict.value?.id !== undefined) {
    airDataInfo.value.districtId = selectedDistrict.value.id
  }

  // 3.添加空气质量信息
  addAirData(airDataInfo.value).then(res => {
    if (res.code === 0) {
      // 4.添加成功给出提示
      showSuccess('Success', res.msg, 1000)

      // 5.刷新列表数据
      refreshAirDataList()

      // 6.关闭表单校验
      submitted.value = false

      // 7.关闭dialog
      showDialog.value = false
    } else {
      showWarn('warn', res.msg, 1000)
    }
  }).catch(err => {
    showError('error', err.msg, 1000)
  })
}

/**
 * 修改空气质量数据
 */
const updateAirData = () => {

  airDataInfo.value.districtId = selectedDistrict.value.id

  updateAirDataInfo(airDataInfo.value).then(res => {
    if (res.code === 0) {

      showSuccess('Success', res.msg, 1000)

      // 刷新列表数据
      refreshAirDataList()

      showDialog.value = false
    } else {
      showWarn('warn', res.msg, 1000)
    }
  }).catch(err => {
    showError('error', err.msg, 1000)
  })
}

/**
 * 关闭Dialog、重置数据操作
 */
const closeDialog = () => {
  // 关闭表单校验
  submitted.value = false

  // 关闭Dialog对话框
  showDialog.value = false

  // 重置数据
  selectedDistrict.value = null

  // 通知父组件 清空 空气数据信息
  emit('clearAirData')
}

/**
 * 刷新数据
 */
const refreshAirDataList = () => {
  // 刷新数据
  emit('refreshAirDataList')
}
</script>

<template>
  <Dialog
    v-model:visible="showDialog"
    maximizable
    modal
    :header="header"
    @hide="closeDialog"
    :style="{ width: '38rem' }"
    :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
    <div style="margin-top: 10px;">
      <div class="field gap-2 mb-5" v-if="airDataInfo.id">
        <span style="color: red;">*</span>
        <label for="pm25" class="font-semibold w-7rem">编号</label>
        <InputText
          id="pm25"
          class="w-full md:w-20rem"
          v-model.trim="airDataInfo.id"
          disabled
          autocomplete="off" />
      </div>
      <div class="field gap-2 mb-5">
        <span style="color: red;">*</span>
        <label for="districtName" class="font-semibold w-7rem">监测区域</label>
        <Dropdown
          placeholder="请选择监测区域"
          class="w-full md:w-20rem"
          :class="{'p-invalid': submitted && !selectedDistrict}"
          required="required"
          v-model.trim="selectedDistrict"
          :options="districtList"
          optionLabel="name" />
        <small v-if="submitted && !selectedDistrict" class="p-invalid" style="color: red;">区域是必需的</small>
      </div>
      <div class="field gap-2 mb-5">
        <span style="color: red;">*</span>
        <label for="monitorTime" class="font-semibold w-7rem">监测日期</label>
        <Calendar
          id="monitorTime"
          class="w-full md:w-20rem"
          :class="{'p-invalid': submitted && !airDataInfo.monitorTime}"
          required="required"
          :showOnFocus="false"
          showIcon
          v-model.trim="airDataInfo.monitorTime" />
        <small v-if="submitted && !airDataInfo.monitorTime" class="p-invalid"
               style="color: red;">监测日期是必需的</small>
      </div>
      <div class="field gap-2 mb-5">
        <span style="color: red;">*</span>
        <label for="pm10" class="font-semibold w-7rem">PM10值</label>
        <InputText
          id="pm10"
          class="w-full md:w-20rem"
          required="required"
          :class="{'p-invalid': submitted && !airDataInfo.pm10}"
          v-model.trim="airDataInfo.pm10"
          autocomplete="off" />
        <small v-if="submitted && !airDataInfo.pm10" class="p-invalid" style="color: red;">pm10是必需的</small>
      </div>
      <div class="field gap-2 mb-5">
        <span style="color: red;">*</span>
        <label for="pm25" class="font-semibold w-7rem">PM2.5值</label>
        <InputText
          id="pm25"
          class="w-full md:w-20rem"
          :class="{'p-invalid': submitted && !airDataInfo.pm25}"
          v-model.trim="airDataInfo.pm25"
          autocomplete="off" />
        <small v-if="submitted && !airDataInfo.pm25" class="p-invalid" style="color: red;">pm2.5是必需的</small>
      </div>
      <div class="field gap-2 mb-5">
        <span style="color: red;">*</span>
        <label for="monitoringStation" class="font-semibold w-7rem">监测站</label>
        <InputText
          id="monitoringStation"
          class="w-full md:w-20rem"
          :class="{'p-invalid': submitted && !airDataInfo.monitoringStation}"
          v-model.trim="airDataInfo.monitoringStation"
          autocomplete="off" />
        <small v-if="submitted && !airDataInfo.monitoringStation" class="p-invalid"
               style="color: red;">监测站是必需的</small>
      </div>
      <div class="field gap-2 mb-5" v-if="airDataInfo.lastModifyTime">
        <span style="color: white;">*</span>
        <label for="lastModifyTime" class="font-semibold w-7rem">最后修改时间</label>
        <InputText id="lastModifyTime" v-model="airDataInfo.lastModifyTime" disabled class="w-full md:w-20rem"
                   autocomplete="off" />
      </div>
    </div>
    <template #footer>
      <Button label="取消" icon="pi pi-times" @click="cancelOperation" severity="secondary" />
      <Button label="确认" icon="pi pi-check" @click="confirmOperation" severity="success" />
    </template>
  </Dialog>
</template>

<style scoped>

</style>